package com.sumainfor.pc.gmio.service.impl;

import com.qiniu.util.Json;
import com.sumainfor.common.Constants;
import com.sumainfor.common.config.RedisUtils;
import com.sumainfor.common.entity.TemplateData;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.CompuUtils;
import com.sumainfor.common.utlis.Jsapi_ticketUtil;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.wechat.WeChatConfig;
import com.sumainfor.pc.gmio.dao.*;
import com.sumainfor.pc.gmio.feign.BaseTenantFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZpcMktFeign;
import com.sumainfor.pc.gmio.feign.Zfeign.ZzuulFeign;
import com.sumainfor.pc.gmio.service.HoHousekeeperService;
import net.bytebuddy.asm.Advice;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.aspectj.apache.bcel.generic.FieldOrMethod;
import org.omg.CORBA.OBJ_ADAPTER;
import org.redisson.misc.Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.auditing.IsNewAwareAuditingHandler;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.el.ELContextEvent;
import javax.swing.undo.AbstractUndoableEdit;
import javax.xml.transform.Result;
import java.math.BigDecimal;
import java.rmi.MarshalledObject;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zc
 * @ClassName HohousekeeperServiceImpl
 * @date 2019/11/30 19:13
 * @description: TODO
 */
@Service
public class HoHousekeeperServiceImpl implements HoHousekeeperService {
    private ReentrantLock lock = new ReentrantLock(false);
    Logger log = LoggerFactory.getLogger(HoHousekeeperServiceImpl.class);


    @Autowired
    HoHousekeeperMapper hoHousekeeperMapper;

    @Autowired
    UtilsMapper utilsMapper;

    @Autowired
    SeTenantBillMapper seTenantBillMapper;

    @Autowired
    SeBillOutlayMapper seBillOutlayMapper;

    @Autowired
    HoWithdrawalMapper hoWithdrawalMapper;

    @Autowired
    HoWithdrawalArticleMapper hoWithdrawalArticleMapper;


    @Autowired
    HoEleMeterMapper hoEleMeterMapper;

    @Autowired
    HoGasMeterMapper hoGasMeterMapper;

    @Autowired
    HoWaterMeterMapper hoWaterMeterMapper;

    @Autowired
    ZpcMktFeign zpcMktFeign;

    @Autowired
    HoPooledMapper hoPooledMapper;
    @Autowired
    HoTenantBillMapper hoTenantBillMapper;
    @Autowired
    SeBillAbnormalMapper seBillAbnormalMapper;
    @Autowired
    RedisUtils redisUtils;

    @Autowired
    ZzuulFeign zzuulFeign;

    @Autowired
    BaseTenantFeign baseTenantFeign;
    /**
     * 查询租客剩余未缴费账单
     * @param params
     * @return
     */
    @Override
    public JsonResult UnpaidBill(Map<String, Object> params) {

        JsonResult result = new JsonResult();
        return result.put(hoHousekeeperMapper.getUnpaidBill(params));
    }

    /**
     * 查询退租当天固定金额水电燃宽已产生的费用
     * @param params
     * @return
     */
    @Override
    public JsonResult getWGEKBill(Map<String, Object> params) {

        //传入参数tenid，
        // HouInfoId,
        // nowtime,(退租时间)
        // StartTime,
        // EndTime,
        // ProOperaType,（1.合租 2.整租）
        // BroadBand,
        // EleFee,
        // IsWater,水费是否是定额定价（0 否 1 是）
        // WaterPricing,
        // IsGas,燃气费是否是定额定价（0 否 1 是）
        // GasPricing,
        // MoviesType(0 智能 1非智能）)
        //最后一次电抄表,租客均摊的电费  EleWithBill
        //最后一次水抄表.租客均摊的水费  WatWithBill
        //最后一次燃抄表,租客均摊的燃气费 GasWithBill

        //ChaId//水电燃收费编号



        Map<String,Object> ChargesMap = hoHousekeeperMapper.getChargeFee(params);//获取签约的收费标准编号
        JsonResult result = new JsonResult();

        Map<String,Object> WatMap = new HashMap<>();
        WatMap.put("TenId",params.get("TenId"));
        WatMap.put("HouInfoId",params.get("HouInfoId"));
        WatMap.put("BiType",2);
        WatMap.put("PubType",1);
        WatMap.put("Status",2);
        WatMap.put("PatStats",2);
        Map<String,Object> WatSum = hoHousekeeperMapper.getGWEBillSum(WatMap);//水费已支付




        Map<String,Object> EleMap = new HashMap<>();
        EleMap.put("TenId",params.get("TenId"));
        EleMap.put("HouInfoId",params.get("HouInfoId"));
        EleMap.put("BiType",2);
        EleMap.put("PubType",2);
        EleMap.put("Status",2);
        EleMap.put("PatStats",2);
        Map<String,Object> EleSum = hoHousekeeperMapper.getGWEBillSum(EleMap);//电费已支付





        Map<String,Object> GasMap = new HashMap<>();
        GasMap.put("TenId",params.get("TenId"));
        GasMap.put("HouInfoId",params.get("HouInfoId"));
        GasMap.put("BiType",2);
        GasMap.put("PubType",3);
        GasMap.put("Status",2);
        GasMap.put("PatStats",2);
        Map<String,Object> GasSum = hoHousekeeperMapper.getGWEBillSum(GasMap);//燃气费已支付





        Map<String,Object> KuanMap = new HashMap<>();
        KuanMap.put("TenId",params.get("TenId"));
        KuanMap.put("HouInfoId",params.get("HouInfoId"));
        KuanMap.put("BiType",2);
        KuanMap.put("PubType",4);
        KuanMap.put("Status",2);
        KuanMap.put("PatStats",2);
        Map<String,Object> KuanSum = hoHousekeeperMapper.getGWEBillSum(KuanMap);//宽带费已支付




        Double   WatYesMoney = MapUtils.getDouble(WatSum,"PayMoneySum");//水费已支付
        Double WatProduceMoney = new Double("0");//水费已产生
        Double WatDrillMoney = new Double("0");//水费应退

        Double EleYesMoney = MapUtils.getDouble(EleSum,"PayMoneySum");//电费已支付
        Double EleProduceMoney = new Double("0");//电费已产生
        Double EleDrillMoney = new Double("0");//电费应退


        Double  GasYesMoney = MapUtils.getDouble(GasSum,"PayMoneySum");//燃气费已支付
        Double GasProduceMoney = new Double("0");//燃气费已产生
        Double GasDrillMoney = new Double("0");//燃气费应退


        Double KuanYesMoney = MapUtils.getDouble(KuanSum,"PayMoneySum");//宽带费已支付
        Double kuanProduceMoney = new Double("0");//宽费已产生
        Double kuanDrillMoney = new Double("0");//宽费应退

        //接受操作的时间 nowTime
        String nowTime = params.get("nowTime").toString();//操作退租的时间
        String endTime = params.get("EndTime").toString();//合同结束时间
        String StartTime = params.get("StartTime").toString();//合同开始时间



        if(DateUtils.differentDays(nowTime, endTime)<=31&&DateUtils.differentDays(nowTime, endTime)>=0){//表示正常退


            //固定金额不退
            //抄表计算最后一次生成的费用+之前抄表生成的公共事业费账单

            WatMap.remove("Status");
            WatMap.remove("PatStats");
            Map<String,Object> WatSumWeiMap = hoHousekeeperMapper.getGWEBillSum(WatMap);//水费已产生


            GasMap.remove("Status");
            GasMap.remove("PatStats");
            Map<String,Object> GasSumWeiMap = hoHousekeeperMapper.getGWEBillSum(GasMap);//燃气费已产生

            KuanMap.remove("Status");
            KuanMap.remove("PatStats");
            Map<String,Object> KuanSumWeiMap = hoHousekeeperMapper.getGWEBillSum(KuanMap);//宽带已产生

            EleMap.remove("Status");
            EleMap.remove("PatStats");
            Map<String,Object> EleSumWeiMap = hoHousekeeperMapper.getGWEBillSum(EleMap);//电费已产生


            kuanProduceMoney = MapUtils.getDouble(KuanSumWeiMap,"BiMoneySum");//宽带已产生
            WatProduceMoney = CompuUtils.add(MapUtils.getDouble(WatSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"WatWithBill"));
            GasProduceMoney = CompuUtils.add(MapUtils.getDouble(GasSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"GasWithBill"));
            EleProduceMoney = CompuUtils.add(MapUtils.getDouble(EleSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"EleWithBill"));

        }else if(DateUtils.differentDays(nowTime, endTime)>31&&(DateUtils.compare_date(StartTime, nowTime, "yyyy-MM-dd").equals("2"))){//退租时间在合同开始之后


            if (MapUtils.getInteger(params,"IsWater")==1){//表示固定金额
               //固定水已产生
                Double WatDanJia =CompuUtils.div(CompuUtils.mul(MapUtils.getDouble(ChargesMap,"WaterPricings"),new Double("12")),new Double("365"),2);//单价
                //WatProduceMoney = CompuUtils.mul(WatDanJia,new Double(DateUtils.differentDays(StartTime, nowTime)));//已产生固定燃气
                WatProduceMoney = CompuUtils.add(WatDanJia,CompuUtils.mul(WatDanJia,new Double(DateUtils.differentDays(StartTime, nowTime))));//CompuUtils.mul(WatDanJia,new Double(DateUtils.differentDays(StartTime, nowTime)));//已产生固定燃气


            }else if (MapUtils.getInteger(params,"IsWater")==0){//表示抄表
                WatMap.remove("Status");
                WatMap.remove("PatStats");
                Map<String,Object> WatSumWeiMap = hoHousekeeperMapper.getGWEBillSum(WatMap);//水费已产生
                WatProduceMoney = CompuUtils.add(MapUtils.getDouble(WatSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"WatWithBill"));//水费已产生
            }

            if(MapUtils.getInteger(params,"BroadBand")>0){//网络固定
                //固定宽已产生
                Double KuanDanJia =CompuUtils.div(CompuUtils.mul(MapUtils.getDouble(params,"BroadBand"),new Double("12")),new Double("365"),2);//单价
               // kuanProduceMoney = CompuUtils.mul(KuanDanJia,new Double(DateUtils.differentDays(StartTime, nowTime)));//已产生固定燃气
                kuanProduceMoney =  CompuUtils.add(KuanDanJia,CompuUtils.mul(KuanDanJia,new Double(DateUtils.differentDays(StartTime, nowTime))));


            }




           if (MapUtils.getInteger(params,"IsGas")==1&&MapUtils.getInteger(params,"ProOperaType")==1&&MapUtils.getInteger(params,"MoviesType")==0){//合租智能固定
               //固定燃气已产生
               Double GasDanJia =CompuUtils.div(CompuUtils.mul(MapUtils.getDouble(ChargesMap,"GasPricings"),new Double("12")),new Double("365"),2);//单价
             //  GasProduceMoney = CompuUtils.mul(GasDanJia,new Double(DateUtils.differentDays(StartTime, nowTime)));//已产生固定燃气
               GasProduceMoney =CompuUtils.add(GasDanJia,CompuUtils.mul(GasDanJia,new Double(DateUtils.differentDays(StartTime, nowTime))));

           }else if(MapUtils.getInteger(params,"IsGas")==0&&MapUtils.getInteger(params,"ProOperaType")==2){//表示整租,抄表
               GasMap.remove("Status");
               GasMap.remove("PatStats");
               Map<String,Object> GasSumWeiMap = hoHousekeeperMapper.getGWEBillSum(GasMap);//燃气费已产生
               GasProduceMoney = CompuUtils.add(MapUtils.getDouble(GasSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"GasWithBill"));


           }

           //电费已产生
          if(MapUtils.getInteger(params,"ProOperaType")==2||(MapUtils.getInteger(params,"MoviesType")==1&&MapUtils.getInteger(params,"ProOperaType")==1)){//整租或者合租非智能抄表
              EleMap.remove("Status");
              EleMap.remove("PatStats");
              Map<String,Object> EleSumWeiMap = hoHousekeeperMapper.getGWEBillSum(EleMap);//电费已产生
              EleProduceMoney = CompuUtils.add(MapUtils.getDouble(EleSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"EleWithBill"));
          }

        }else if(DateUtils.compare_date(nowTime, StartTime, "yyyy-MM-dd").equals("2")){ //提前退


            if (MapUtils.getInteger(params,"IsWater")==1){//表示固定金额
                WatProduceMoney = new Double("0");
            }else if (MapUtils.getInteger(params,"IsWater")==0){//表示抄表
                WatMap.remove("Status");
                WatMap.remove("PatStats");
                Map<String,Object> WatSumWeiMap = hoHousekeeperMapper.getGWEBillSum(WatMap);//水费已产生
                WatProduceMoney = CompuUtils.add(MapUtils.getDouble(WatSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"WatWithBill"));//水费已产生
            }

            if(MapUtils.getInteger(params,"BroadBand")>0){//网络固定

                kuanProduceMoney = new Double("0");
            }


            if (MapUtils.getInteger(params,"IsGas")==1&&MapUtils.getInteger(params,"ProOperaType")==1&&MapUtils.getInteger(params,"MoviesType")==0){//合租智能固定

                GasProduceMoney =  new Double("0");

            }else if(MapUtils.getInteger(params,"IsGas")==0&&MapUtils.getInteger(params,"ProOperaType")==2){//表示整租,抄表
                GasMap.remove("Status");
                GasMap.remove("PatStats");
                Map<String,Object> GasSumWeiMap = hoHousekeeperMapper.getGWEBillSum(GasMap);//燃气费已产生
                GasProduceMoney = CompuUtils.add(MapUtils.getDouble(GasSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"GasWithBill"));
            }

            //电费已产生
            if(MapUtils.getInteger(params,"ProOperaType")==2||(MapUtils.getInteger(params,"MoviesType")==1&&MapUtils.getInteger(params,"ProOperaType")==1)){//整租或者合租非智能抄表
                EleMap.remove("Status");
                EleMap.remove("PatStats");
                Map<String,Object> EleSumWeiMap = hoHousekeeperMapper.getGWEBillSum(EleMap);//电费已产生
                EleProduceMoney = CompuUtils.add(MapUtils.getDouble(EleSumWeiMap,"BiMoneySum"),MapUtils.getDouble(params,"EleWithBill"));
            }

        }else if(DateUtils.compare_date(endTime, nowTime, "yyyy-MM-dd").equals("2")){//延期退


        }

        Map<String,Object> endMap = new HashMap<>();//最后返回给前端的参数
        endMap.put("WatYesMoney",WatYesMoney);//水费已支付
        endMap.put("WatProduceMoney",WatProduceMoney);//水费已产生
        WatDrillMoney = CompuUtils.reduce(WatProduceMoney,WatYesMoney);
        endMap.put("WatDrillMoney",WatDrillMoney);//水费应补缴
        endMap.put("EleYesMoney",EleYesMoney);//电费已支付
        endMap.put("EleProduceMoney",EleProduceMoney);//电费已产生
        EleDrillMoney = CompuUtils.reduce(EleProduceMoney,EleYesMoney);
        endMap.put("EleDrillMoney",EleDrillMoney);//电费应补缴
        endMap.put("GasYesMoney",GasYesMoney);//燃气已支付
        endMap.put("GasProduceMoney",GasProduceMoney);//燃气已产生
        GasDrillMoney = CompuUtils.reduce(GasProduceMoney,GasYesMoney);
        endMap.put("GasDrillMoney",GasDrillMoney);//燃气应补缴
        endMap.put("KuanYesMoney",KuanYesMoney);//宽带已支付
        endMap.put("kuanProduceMoney",kuanProduceMoney);//宽带已产生
        kuanDrillMoney = CompuUtils.reduce(kuanProduceMoney,KuanYesMoney);
        endMap.put("kuanDrillMoney",kuanDrillMoney);//宽带应补缴
        return result.put(endMap);
    }

    /**
     * 退租
     * @param params
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult addHouseKeeper(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        lock.lock();//加锁操作

        try {
            try {


//                if (params.get("openid")==null || params.get("ComName")==null || params.get("Address")==null
//                        || params.get("PaId")==null || params.get("ProOperaType")==null || params.get("HouId")==null
//                        || params.get("HouInfoId")==null || params.get("MiId")==null
//                        || params.get("DelIdList")==null || params.get("InteDeviceList")==null ||  params.get("inteType")==null
//                        ||params.get("ifIntelligentDevice")==null ){
//                    return result.putFailed("参数不正确");
//                }
                //退租总金额(取绝对值)
                BigDecimal TotalMoney=new BigDecimal(params.get("TotalMoney").toString()).abs();
                String userId=ContextUtils.getUserId();//当前登录人编号
                //退租主表编号
                String UUID="";
                Map<String,Object>uuid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "WitId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_withdrawal");
                }});
                System.out.println("uuid"+uuid);
                if(uuid!=null){
                    int number=Integer.valueOf(uuid.get("uuid").toString());
                    UUID= ComUtils.getLocalTrmSeqNum("te",number);
                }else{
                    UUID=ComUtils.getLocalTrmSeqNum("te",0);
                }
                params.put("WitId",UUID);//房源退租主表编号
                params.put("by", ContextUtils.getUserId());//操作人
                params.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("StartingTime",params.get("instm"));//发起时间
                params.put("LaunchId",ContextUtils.getUserId());//发起人编号
                //正数收入 负数支出(退租结算生成账单);
                if (params.get("IfNumber").toString().equals("1")){//0 正数 1负数
                    params.put("IsIncome","0");//退租账单类型    0.唐巢收入    1.唐巢支出
                    //收入账单编号
                    String BiId="";
                    Map<String,Object>bid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "BiId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_tenant_bill");
                    }});
                    if(uuid!=null){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        BiId= ComUtils.getLocalTrmSeqNum("te",number);
                    }else{
                        BiId=ComUtils.getLocalTrmSeqNum("te",0);
                    }
                    //组装 收入账单参数
                    Map<String,Object> map=new HashMap<String, Object>();
                    map.put("by", ContextUtils.getUserId());//操作人
                    map.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    map.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(map);
                    map.put("BiId",BiId);//账单编号 UUID
                    map.put("CorId",params.get("CorId"));//当前账单归属公司
                    map.put("BiName","退租账单");//账单名称
                    map.put("IfTemporary",0);//是否是临时账单    0.否   1.是
                    map.put("BiType",6);//房租 2.公共事业费  3.维修费用  \n4.延期退审核  5.其他费用  6.退租账单
                    map.put("Source",UUID);//账单来源编号（根据账单类型退租账单主表编号）
                    map.put("FirstMon",0);//房租账单是否是首月    0否   1.是
                    map.put("PubType",0);//公共事业费的费用类型  0无  1.水费  2.电费  3.燃气\n只有账单类型为2才有
                    map.put("BiMoney",TotalMoney);//账单金额
                    map.put("BillExplain","费用合计:"+TotalMoney);//账单金额说明,多个逗号隔开
                    map.put("BiGenerated",params.get("instm"));//账单生成日
                    map.put("EndTime",params.get("instm"));//账单结束时间
                    map.put("LateDay",params.get("instm"));//账单最晚付款日
                    map.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是\n水电燃房租不可调整  类型 1-2
                    map.put("TenId",params.get("TenId"));//客户编号
                    map.put("HouId",params.get("HouId"));//房源主表编号
                    map.put("HouInfoId",params.get("HouInfoId"));//房源详表编号
                    map.put("Create",userId);//操作人
                    map.put("CreateType","2");//账单创建人类型  1.系统  2.人为
                    map.put("ExpStatus","0");//账单逾期状态   0.未逾期  1逾期   （超过最晚状态还未支付）
                    map.put("Status","1");//账单状态   1.待支付  2.支付完成  3待审核   4.账单废弃（租客违约）
                    map.put("Abnormal","0");//账单异常状态   0正常   1异常
                    Integer count=seTenantBillMapper.addTenantBill(map);
                    if (count<=0){
                        log.debug("退租账单异常--收入");
                        return result.putFailed("服务器繁忙");
                    }
                }else{
                    params.put("IsIncome","1");//退租账单类型    0.唐巢收入    1.唐巢支出
                    //唐巢支出账单
                    String BiOutId="";
                    Map<String,Object> boid=utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "BiOutId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_bill_outlay");
                    }});
                    if(uuid!=null){
                        int number=Integer.valueOf(uuid.get("uuid").toString());
                        BiOutId= ComUtils.getLocalTrmSeqNum("te",number);
                    }else{
                        BiOutId=ComUtils.getLocalTrmSeqNum("te",0);
                    }
                    //组装 支出账单参数
                    Map<String,Object> map=new HashMap<String, Object>();
                    map.put("by", ContextUtils.getUserId());//操作人
                    map.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    map.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(map);
                    map.put("BiOutId",BiOutId);//账单编号 UUID
                    map.put("CorId",params.get("CorId"));//当前账单归属公司
                    map.put("BiOutName","退租账单");//账单名称
                    map.put("IfTemporary",0);//是否是临时账单    0.否   1.是
                    map.put("BiOutType",3);//账单类型  1.业主   2.供应商  3.退租账单   4.公共事业费    4.账单撤回
                    map.put("Relation",UUID);//账单来源编号（根据账单类型退租账单主表编号）
                    map.put("FirstMon",0);//房租账单是否是首月    0否   1.是
                    map.put("PubType",0);//公共事业费的费用类型  0无  1.水费  2.电费  3.燃气\n只有账单类型为2才有
                    map.put("BiMoney",TotalMoney);//账单金额
                    map.put("BillExplain","费用合计:"+TotalMoney);//账单金额说明,多个逗号隔开
                    map.put("StartTime",params.get("instm"));//账单生成日
                    map.put("EndTime",params.get("instm"));//账单结束时间
                    map.put("LateDay",params.get("instm"));//账单最晚付款日
                    map.put("IfAdjust",0);//当前账单是否可以调整   0.否  1.是\n水电燃房租不可调整  类型 1-2
                    map.put("StemType",3);//支出类型   1.业主  2.供应商  3.租客
                    map.put("StemId",params.get("TenId"));//客户编号 支出关联人编号，根据支出类型
                    map.put("HouId",params.get("HouId"));//房源主表编号
                    map.put("HouInfoId",params.get("HouInfoId"));//房源详表编号
                    map.put("Create",userId);//操作人
                    map.put("CreateType","2");//账单创建人类型  1.系统  2.人为
                    map.put("Create",params.get("insby"));//账单创建人 如果类型为系统，该字段为空
                    map.put("ExpStatus",0);//账单逾期状态   0.未逾期  1逾期   （超过最晚状态还未支付）
                    map.put("Status",1);//账单状态   1.待支付  2.支付完成  3待审核   4.账单废弃（租客违约）
                    Integer count=seBillOutlayMapper.addSeBillOutlay(map);
                    if (count<=0){
                        log.debug("退租账单异常--支出");
                        return result.putFailed("服务器繁忙");
                    }
                }
                //退租主表
                params.put("AuditId",ContextUtils.getUserId());//审核人
                params.put("AuditTime",params.get("instm"));//审核时间
                System.out.println("params"+params);
                hoWithdrawalMapper.addHoWithdrawal(params);
                //房源物品清单参数
                List<Map<String,Object>> artList=(List<Map<String,Object>>)params.get("articleList");
                System.out.println("artList"+artList);
                if(artList.size()>0) {
                    for (int i = 0; i < artList.size(); i++) {
                        Map<String, Object> artMap = artList.get(i);
                        artMap.put("WitId", params.get("WitId"));
                        artMap.put("HouId", params.get("HouId"));//房源主表编号
                        artMap.put("HouInfoId", params.get("HouInfoId"));//房源详表编号
                        artMap.put("OldAmount", artMap.get("ComNumber"));//房源原数量
                        artMap.put("RecyclingAmount", artMap.get("RealComNumber"));//回收数量（实际数量、不会大于原数量）
                        artMap.put("instm", params.get("instm"));
                        artMap.put("insterm", params.get("insterm"));
                        artMap.put("insby", params.get("insby"));
                        artMap.put("insfnc", params.get("insfnc"));
                        hoWithdrawalArticleMapper.addHoWithdrawalArticle(artMap);
                    }
                }

//////////////////////////////////////////////////////////////////////////////////
                ////////公共事业费记录抄表数////////////////////
//////////////////////////////////////////////////////////////////////////////////
                //(公共事业费)参数,EleMap,WatMap,GasMap
//                WatMap{
//                    "HouId",
//                    "HouInfoId",
//                    "LastMonthRead",
//                    "ThisMonthRead",
//                }
                //先走水费
                if (params.get("WatMap")!=null) {
                    Map<String, Object> WatMap = (Map<String, Object>) params.get("WatMap");

                    String WatmeIdUUID = "";//水费抄表编号
                    String BatchIdUUID = "";//水费抄表批次编号
                    Map<String, Object> WameIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "WameId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_water_meter");
                    }});

                    if (WameIduuid != null) {
                        int number = Integer.valueOf(WameIduuid.get("uuid").toString());
                        WatmeIdUUID = ComUtils.getLocalTrmSeqNum("WM0", number);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", number);
                    } else {
                        WatmeIdUUID = ComUtils.getLocalTrmSeqNum("WM0", 0);
                        BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", 0);
                    }
                    WatMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    WatMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(WatMap);
                    WatMap.put("WameId", WatmeIdUUID);//水费抄表编号
                    WatMap.put("BatchId", BatchIdUUID);//水费抄表批次编号
                    WatMap.put("MeTypeId", UUID);//来源编号
                    WatMap.put("IfMeter", 1);//是否是退租抄表

                    // Watmap.put("HouId",map1.get("HouId"));//房源编号
                    // Watmap.put("HouInfoId", map1.get("HouInfoId"));//房源详表编号
                    WatMap.put("IfOperaType", 1);//是否整租 0否 1是 2秘书抄表
                    //  Watmap.put("StaTime",map1.get("GenerateTime"));//账单起时间
                    // Watmap.put("EndTime",GenerateTimeNow);//账单止时间
                    //  Watmap.put("LastMonthRead",map1.get("LastMonthRead"));//上月总表数
                    // Watmap.put("ThisMonthRead", map1.get("ThisMonthRead"));//本次总表数
                    WatMap.put("MeterRole", 2);//抄表人角色0租赁顾问 1服务秘书 2服务管家
                    //  Watmap.put("BillMoney",billMoney);//账单金额.所有租客一共需支付的金额
                    WatMap.put("GenerateTime", params.get("StartingTime"));//抄表日期
                    WatMap.put("Recorder", ContextUtils.getUserId());//记录人编号
                    WatMap.put("IfGenerate", 1);//是否生成账单 0未生成 1已生成

                    if (MapUtils.getInteger(params, "ProOperaType") == 1 && MapUtils.getInteger(params, "MoviesType") == 1) {//合租非智能
                         //总的均摊量
                        Double  WatPooledSum = CompuUtils.reduce(MapUtils.getDouble(WatMap,"ThisMonthRead"),MapUtils.getDouble(WatMap,"LastMonthRead"));
                        Double WatPooled = new Double("0");//在租房间的均摊电量

                        WatMap.put("IfApportion", 1);//是否需要分摊0否 1是
                        Integer a1 = hoWaterMeterMapper.addHoWaterMeter(WatMap);
                        if (a1<=0){
                            return  result.putFailed("新增水抄表失败");
                        }
                        List<Map<String,Object>> getHouPact = zpcMktFeign.getHouPact(WatMap);
                        if (getHouPact.size()>0){
                           //在租房间的均摊量
                            WatPooled = CompuUtils.div(WatPooledSum,new Double(getHouPact.size()),2);
                        }
                        for(Map<String,Object> map1:getHouPact){
                            String WatPooledIduuid = "";
                            Map<String, Object> PooledIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                                put("uuid", "WatPooledId");
                                put("database", Constants.DATA_SOURCE_GMIO);
                                put("surface", "tcgmio_water_meter_Pooled");
                            }});

                            if (PooledIduuid != null) {
                                int number = Integer.valueOf(PooledIduuid.get("uuid").toString());
                                WatPooledIduuid = ComUtils.getLocalTrmSeqNum("WP", number);
                            } else {
                                WatPooledIduuid = ComUtils.getLocalTrmSeqNum("WP", 0);
                            }

                            Map<String,Object> WatPolMap = new HashMap<>();
                            WatPolMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                            WatPolMap.put("fnc",
                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                            ParamsCommon.commonInsertParms(WatPolMap);

                            WatPolMap.put("WatPooledId", WatPooledIduuid);//公摊水表编号
                            WatPolMap.put("WameId",WatMap.get("WameId"));//水抄表编号
                            WatPolMap.put("BatchId", WatMap.get("BatchId"));//水抄表批次编号
                            WatPolMap.put("TenId", map1.get("TenId"));//租客编号
                            WatPolMap.put("HouId", map1.get("HouId"));//房源编号
                            WatPolMap.put("HouInfoId", map1.get("HouInfoId"));//房源详表编号
                            WatPolMap.put("WatPooled", WatPooled);//公摊用水量
                            WatPolMap.put("WatMetMoney",CompuUtils.mul(MapUtils.getDouble(map1,"WaterPricing"),WatPooled));//记录在租房间的公摊水费
                            WatPolMap.put("PoolTime", params.get("StartingTime"));//公摊生成时间

                            if (params.get("TenId").equals(map1.get("TenId"))){
                                Double WatMetMoney = MapUtils.getDouble(WatPolMap,"WatMetMoney");
                                List<Map<String,Object>> getPooledList=hoPooledMapper.getPooledList(map1);//查询租客未生成账单的公摊费用
                                if (getPooledList.size()>0){//表示本次抄表之前有公摊费用未生成账单,要加上之前的公摊费用一起生成账单,
                                    for (Map<String,Object> map2:getPooledList){
                                        WatMetMoney = CompuUtils.add(WatMetMoney,MapUtils.getDouble(map2,"WatMetMoney"));
                                        //修改公摊费用为已生成账单
                                        Map<String,Object> PoolMap = new HashMap<>();
                                        PoolMap.put("term","4");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                                        PoolMap.put("fnc",
                                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                                        ParamsCommon.commonUpdateParms(PoolMap);
                                        PoolMap.put("WatPooledId",map2.get("WatPooledId"));//公摊账单编号
                                        PoolMap.put("Status",1);//租客水费公摊表已生成账单
                                        PoolMap.put("IfGenerate",1);//水抄表已生成账单
                                        Integer a8 = hoPooledMapper.updateWatPooled(PoolMap);
                                        if (a8<=0){
                                            return result.putFailed("修改租客公摊表失败");

                                        }

                                    }
                                }

                                WatPolMap.put("WatMetMoney",WatMetMoney);//是否生成账单0未生成1已生成
                                WatPolMap.put("Status", 1);//是否生成账单0未生成1已生成

                            }else{//其他房间生成均摊不生成账单
                                WatPolMap.put("Status", 0);//是否生成账单0未生成1已生成

                            }
                          Integer a2 = hoPooledMapper.addWatPooled(WatPolMap);
                            if (a2<=0){
                                return result.putFailed("新增房间公摊表失败");
                            }

                        }
                    } else if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租抄水费
                        WatMap.put("IfApportion", 0);//是否需要分摊0否 1是
                        Integer a3 = hoWaterMeterMapper.addHoWaterMeter(WatMap);
                        if (a3<=0){
                            return result.putFailed("新增整租水抄表失败");
                        }
                    }

                }

//////////////////////////////////////////////////////////////////////////////////////
//                GasMap{
//                    "HouId",
//                    "HouInfoId",
//                    "LastMonthRead",
//                    "ThisMonthRead",
//                }

             //在走燃气费
             if (MapUtils.getInteger(params,"ProOperaType")==2){//整租记录本次燃气费

                 if (params.get("GasMap")!=null) {
                     Map<String,Object> GasMap = (Map<String, Object>) params.get("GasMap");
                     String GasmeIdUUID = "";//燃气抄表编号
                     String GasBatchIdUUID = "";//燃气抄表批次编号
                     Map<String, Object> GasmeIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                         put("uuid", "GasmeId");
                         put("database", Constants.DATA_SOURCE_GMIO);
                         put("surface", "tcgmio_gas_meter");
                     }});

                     if (GasmeIduuid != null) {
                         int number = Integer.valueOf(GasmeIduuid.get("uuid").toString());
                         GasmeIdUUID = ComUtils.getLocalTrmSeqNum("GM0", number);
                         GasBatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", number);
                     } else {
                         GasmeIdUUID = ComUtils.getLocalTrmSeqNum("GM0", 0);
                         GasBatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", 0);
                     }

                     GasMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                     GasMap.put("fnc",
                             this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                     ParamsCommon.commonInsertParms(GasMap);
                     GasMap.put("GasmeId", GasmeIdUUID);//燃气费抄表编号
                     GasMap.put("BatchId", GasBatchIdUUID);//批次编号
                     GasMap.put("IfOperaType", 1);//是否整租0否1是
                     GasMap.put("MeTypeId",UUID);//来源编号
                     GasMap.put("IfMeter",1);//退租抄表
                     //GasMap.put("MeterRole",2);//退租抄表
                     //GasMap.put("StaTime",2);//账单起时间
                     //GasMap.put("EndTime",2);//账单止时间
                     GasMap.put("MeterRole", 2);//抄表人角色2服务管家
                     GasMap.put("Recorder", ContextUtils.getUserId());//记录人编号
                     GasMap.put("IfApportion", 0);//是否需要分摊0否1是
                     GasMap.put("IfGenerate", 1);//是否生成账单
                     GasMap.put("GenerateTime", params.get("StartingTime"));
                     Integer a4 = hoGasMeterMapper.addHoGasMeter(GasMap);//记录最后一次管家退租的抄表数
                    if (a4<=0){
                       return result.putFailed("新增燃气抄表数失败");
                    }

                 }

             }

///////////////////////////////////////////////////////////////////////////////////////
//                EleMap{
//                 "HouId"
//                 "HouInfoId"
//                `LastMonthEleSum`  '上月总表',
//                `LastMonthElePeak` '上月峰时',
//                `LastMonthEleFlat` '上月谷时',
//                `ThisMonthEleSum`  '总表   （不能低于上月）',
//                `ThisMonthElePeak`  '峰时   （不能低于上月）',
//                `ThisMonthEleFlat` '谷时',
//                "roomData":[
//                    "HouInfoId":
//                    `LastMonthEleSum`  '上月总表',
//                    `ThisMonthEleSum`  '总表   （不能低于上月）',
//                        ]
//                }

              //在走电费
                if (params.get("EleMap") !=null){
                    Map<String,Object> EleMap = (Map<String, Object>) params.get("EleMap");

                    String Eleus  = "";//电费抄表批次编号
                    //电
                    Map<String,Object> Eleuuid =utilsMapper.getUUID(new HashMap<String,Object>(){{
                        put("uuid", "ElemeId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_ele_meter");
                    }});
                    int numberss = 0;
                    if(Eleuuid!=null){
                        numberss=Integer.valueOf(Eleuuid.get("uuid").toString());
                        Eleus = ComUtils.getLocalTrmSeqNum("BA0",numberss);
                    }else{
                        Eleus = ComUtils.getLocalTrmSeqNum("BA0",0);
                    }

                    Map<String,Object> EleWater = new HashMap<>();//先生成公共区域的
                    EleWater.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    EleWater.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(EleWater);
                    EleWater.put("ElemeId", ComUtils.getLocalTrmSeqNum("EM" + 0, numberss));//电费抄表编号(公共区域)
                    EleWater.put("BatchId", Eleus);//批次编号
                    EleWater.put("HouId", EleMap.get("HouId"));//房源编号
                    EleWater.put("HouInfoId", EleMap.get("HouInfoId"));//公共区域的房源详表编号
                    EleWater.put("IfOperaType", 1);//是否整租0否1是
                    EleWater.put("MeTypeId", UUID);//来源编号
                    EleWater.put("IfMeter", 1);//是退租抄表
                    EleWater.put("LastMonthEleSum", EleMap.get("LastMonthEleSum"));//上次总表
                    EleWater.put("LastMonthElePeak", EleMap.get("LastMonthElePeak"));//上次峰表
                    EleWater.put("LastMonthEleFlat", EleMap.get("LastMonthEleFlat"));//上次谷表
                    EleWater.put("ThisMonthEleSum", EleMap.get("ThisMonthEleSum"));//总表
                    EleWater.put("ThisMonthElePeak", EleMap.get("ThisMonthElePeak"));//峰表
                    EleWater.put("ThisMonthEleFlat", EleMap.get("ThisMonthEleFlat"));//谷表
                    EleWater.put("GenerateTime", params.get("StartingTime"));//抄表日期
                    EleWater.put("MeterRole", 2);//服务管家
                    EleWater.put("Recorder", ContextUtils.getUserId());//记录人编号
                    EleWater.put("IfGenerate", 1);//是否生成账单0未生成 1已生成
                    if (MapUtils.getInteger(params,"ProOperaType")==1&&MapUtils.getInteger(params,"MoviesType")==1) {//表示合租非智能

                        //先生成合租非智能的公共区域的
                        Double perEleSum = CompuUtils.reduce(MapUtils.getDouble(EleMap,"ThisMonthEleSum"),MapUtils.getDouble(EleMap,"LastMonthEleSum"));
                       // Double perELeMoney = CompuUtils.mul(perEleSum,MapUtils.getDouble(params,"EleFee"));
                        EleWater.put("perEleSum", perEleSum);//公摊电量
                       // EleWater.put("perELeMoney", perELeMoney);//公摊金额
                        hoEleMeterMapper.addHoEleMeter(EleWater);

                        //在生成房间的
                        List<Map<String, Object>> getHouPact = zpcMktFeign.getHouPact(EleMap);//获取房源在租租客
                        List<Map<String, Object>> roomData = (List<Map<String, Object>>) EleMap.get("roomData");

                        Double lastSum = new Double("0");
                        Double NowSum = new Double("0");
                        for (Map<String, Object> map5 : roomData) {
                            lastSum = CompuUtils.add(lastSum, MapUtils.getDouble(map5, "LastMonthEleSum"));
                            NowSum = CompuUtils.add(NowSum, MapUtils.getDouble(map5, "ThisMonthEleSum"));
                        }
                        //本次总的均摊
                        Double ElePooled = CompuUtils.reduce(CompuUtils.reduce(MapUtils.getDouble(EleMap, "ThisMonthEleSum"), NowSum), CompuUtils.reduce(MapUtils.getDouble(EleMap, "LastMonthEleSum"), lastSum));
                        //获取在租房间本次管家抄表的均摊电量
                        Double perELeSum = CompuUtils.div(ElePooled, new Double(getHouPact.size()), 2);
                        for (int i = 0; i < roomData.size(); i++) {
                            Map<String, Object> roomMapone = new HashMap<>();
                            roomMapone.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                            roomMapone.put("fnc",
                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                            ParamsCommon.commonInsertParms(roomMapone);
                            roomMapone.put("ElemeId", ComUtils.getLocalTrmSeqNum("EM" + (i + 1), numberss));//电费抄表编号(公共区域)
                            roomMapone.put("BatchId", Eleus);//批次编号
                            roomMapone.put("MeTypeId", UUID);//来源编号
                            roomMapone.put("IfMeter", 1);//是退租抄表
                            roomMapone.put("HouId", EleWater.get("HouId"));//房源编号
                            roomMapone.put("HouInfoId", roomData.get(i).get("HouInfoId"));//其他房间的房源详表编号
                            roomMapone.put("IfOperaType", 0);//是否整租0否1是
                            roomMapone.put("LastMonthEleSum", roomData.get(i).get("LastMonthEleSum"));//上次总表
                            roomMapone.put("ThisMonthEleSum", roomData.get(i).get("ThisMonthEleSum"));//总表
                            roomMapone.put("MeterRole", 2);//服务管家
                            roomMapone.put("GenerateTime", params.get("StartingTime"));//抄表日期
                            roomMapone.put("Recorder", ContextUtils.getUserId());//记录人编号
                            for (Map<String, Object> map8 : getHouPact) {//该房源在租房间
                                //表示退租的房间刚好是操作的
                                if (roomMapone.get("HouInfoId").equals(MapUtils.getString(map8, "HouInfoId"))&&
                                    roomMapone.get("HouInfoId").equals(MapUtils.getString(params,"HouInfoId"))&&
                                    MapUtils.getString(map8, "HouInfoId").equals(MapUtils.getString(params,"HouInfoId"))
                                ) {


                                    Double ceshi = CompuUtils.add(perELeSum,CompuUtils.reduce(MapUtils.getDouble(roomMapone,"ThisMonthEleSum"),MapUtils.getDouble(roomMapone,"LastMonthEleSum")));
                                    roomMapone.put("IfGenerate", 1);//是否生成账单0未生成 1已生成
                                    roomMapone.put("perELeSum", ceshi);//房间均摊电量
                                    roomMapone.put("perELeMoney", CompuUtils.mul(ceshi, MapUtils.getDouble(map8, "EleFee")));//房间均摊金额

                                    Double perELeMoney = MapUtils.getDouble(roomMapone,"perELeMoney");


                                    List<Map<String,Object>> getElePoodList = hoEleMeterMapper.getHouInEle(map8);//获取房间已生成均摊未生成账单的抄表编号
                                    if (getElePoodList.size()>0){
                                        for (Map<String,Object> map2:getElePoodList){
                                            perELeMoney = CompuUtils.add(perELeMoney,MapUtils.getDouble(map2,"perELeMoney"));//获取当前在租组可所租房间的之前的未生成账单的均摊两
                                            //修改未生成账单的均摊量为已生成账单
                                            Map<String,Object> EleMaps = new HashMap<>();
                                            EleMaps.put("term","4");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                                            EleMaps.put("fnc",
                                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                                            ParamsCommon.commonUpdateParms(EleMaps);
                                            EleMaps.put("IfGenerate",1);//1表示生成账单 0未生成账单
                                            EleMaps.put("ElemeId",map2.get("ElemeId"));//电抄表编号
                                            Integer a1 = hoEleMeterMapper.updateHoEleDelfg(EleMaps);
                                            if (a1<=0){
                                                return result.putFailed("修改该房源之前未生成均摊的电量失败");
                                            }

                                        }

                                    }
                                    roomMapone.put("perELeMoney",perELeMoney);//房间均摊金额
                                }
                                if (roomMapone.get("HouInfoId").equals(MapUtils.getString(map8,"HouInfoId"))&&!roomMapone.get("HouInfoId").equals(MapUtils.getString(params,"HouInfoId"))){
                                    Double ceshi = CompuUtils.add(perELeSum,CompuUtils.reduce(MapUtils.getDouble(roomMapone,"ThisMonthEleSum"),MapUtils.getDouble(roomMapone,"LastMonthEleSum")));
                                    roomMapone.put("IfGenerate", 0);//是否生成账单0未生成 1已生成
                                    roomMapone.put("perELeSum", ceshi);//房间均摊电量
                                    roomMapone.put("perELeMoney", CompuUtils.mul(ceshi, MapUtils.getDouble(map8, "EleFee")));//房间均摊金额
                                }
                            }
                            Integer aw = hoEleMeterMapper.addHoEleMeter(roomMapone);//记录本次房间抄表
                            if (aw<=0){
                                return result.putFailed("新增房间电抄表失败");
                            }
                        }

                    }else if (MapUtils.getInteger(params,"ProOperaType")==2){//表示整租
                    //只生成公共区域的
                        Double perEleSum = CompuUtils.reduce(MapUtils.getDouble(EleMap,"ThisMonthEleSum"),MapUtils.getDouble(EleMap,"LastMonthEleSum"));
                        Double perELeMoney = CompuUtils.mul(perEleSum,MapUtils.getDouble(params,"EleFee"));
                        EleWater.put("perEleSum", perEleSum);//公摊电量
                        EleWater.put("perELeMoney", perELeMoney);//公摊金额
                       Integer aa =  hoEleMeterMapper.addHoEleMeter(EleWater);
                       if (aa<=0){
                           return result.putFailed("新增公共区域抄表失败");
                       }
                    }
                }



                /////////////////////////////////////////////////////////
                //    退租                          //////////////////
                /*******************判断是否需要审核***********************************/
                if (params.get("Status").toString().equals("1")){//如果需要审核即审核时再去推送
                    //组装消息通知参数
                    Map<String,Object> messageMap=new HashMap<String,Object>();
                    messageMap.put("MeType","4");//4.市场部-服务中心经理
                    messageMap.put("Title","退租账单审核");//4.市场部-服务中心经理
                    messageMap.put("IfJump","0");//是否可以跳转页面 0.否 1.是
                    // messageMap.put("Neturl","4");//跳转URL（sys-sell/contact）
                    messageMap.put("by", "auto");//操作人
                    messageMap.put("term", "2");// 更新端 Update端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                    messageMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(messageMap);
                    messageMap.put("Content",messageMap.get("instm")+"注意！有新的退租账单待审核 请及时处理！");//4.市场部-服务中心经理
                    //去市场部新增消息通知
                    JsonResult zuulResult=zzuulFeign.addMessage(messageMap);
                    if (zuulResult.get("errorCode")!=null && !zuulResult.get("errorCode").toString().equals("0")){
                        return result.putFailed("服务器繁忙");
                    }
                    //账单异常记录
                    params.put("Abnor",1);//违约金异常类型  0无状态  1.租客违约   2.唐巢违约\n只有退租账单才有该编号
                    params.put("BillType","2");//账单异常分类   1.房租（合同）   2.退租账单
                    params.put("Source",params.get("PaId"));//账单异常来源编号（那一笔账单异常）
                    params.put("SysUserId",ContextUtils.getUserId());
                    seBillAbnormalMapper.addSeBill(params);
                    result.putSuccess("操作成功");
                }else {

                    //根据合同编号获取房间的智能门锁的列表
                    JsonResult TenResult = baseTenantFeign.getTenPhone(params);
                    Map<String,Object> TenMap = (Map<String, Object>) TenResult.get("result");
                    params.put("phone",TenMap.get("TenPhone"));//添加租客手机号




                    //智能门锁的数据
                    List<Map<String, Object>> identifierList = new ArrayList<>();
                    JsonResult resultRoom = zpcMktFeign.getIntelligentRoom(params);
                    Map<String, Object> IntellMap = (Map<String, Object>) resultRoom.get("result");
                    Integer IntelligentOpenType = new Integer("0");
                    if (IntellMap != null) {
                        IntelligentOpenType = MapUtils.getInteger(IntellMap,"IntelligentOpenType");
                        if (MapUtils.getString(IntellMap, "IntelligentRoom") != null && !MapUtils.getString(IntellMap, "IntelligentRoom").equals("")) {
                            String IntelligentRoom = MapUtils.getString(IntellMap, "IntelligentRoom");
                            String IntelligentRooms = IntelligentRoom.substring(0, IntelligentRoom.length() - 1);
                            String[] arr1 = IntelligentRooms.split(",");
                            for (String arrStr : arr1) {
                                Map<String, Object> identMap = new HashMap<>();
                                identMap.put("Intelligent", IntellMap.get("IntelligentType"));//锁类型
                                identMap.put("Identifier", arrStr.substring(0, arrStr.indexOf(":")));//锁编号
                                identMap.put("CodeId", arrStr.substring(arrStr.indexOf(":") + 1));//钥匙
                                identifierList.add(identMap);
                            }
                        }
                    }

                    if(identifierList.size()>0){
                    for (Map<String, Object> InteMap : identifierList) {
                        //Intelligent 0.蜂电   1.大华   2.科技侠   3.果加
                        if (InteMap.get("Intelligent").toString().equals("2")) {
                            String DeviceLockToken = redisUtils.get("DeviceLockToken");
                            //如果获取不到就重新登录
                            if (DeviceLockToken == null) {
                                Map<String, Object> tokenMap = new HashMap<String, Object>();
                                params.put("client_id", InteDeviceLockConfig.CLIENT_ID);
                                params.put("client_secret", InteDeviceLockConfig.CLIENT_SECRET);
                                params.put("grant_type", InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
                                params.put("username", InteDeviceLockConfig.USERNAME);
                                params.put("password", InteDeviceLockConfig.PASSWORD);
                                params.put("redirect_uri", InteDeviceLockConfig.REDIRECT_URL);
                                tokenMap = InteDeviceLockUtil.oauth2Token(params);
                                if (tokenMap.get("access_token") != null) {
                                    DeviceLockToken = tokenMap.get("access_token").toString();
                                    //token存到redis中
                                    redisUtils.set("DeviceLockToken", DeviceLockToken, Long.valueOf(tokenMap.get("expires_in").toString()));
                                } else {
                                    return result.putFailed("token获取失败");
                                }
                            }

                            Map<String, Object> sendMap = new HashMap<>();
                            sendMap.put("clientId", InteDeviceLockConfig.CLIENT_ID);//应用编号
                            sendMap.put("accessToken", DeviceLockToken);//访问令牌
                            sendMap.put("lockId", InteMap.get("Identifier"));//智能设备编号
                            //sendMap.put("keyId", InteMap.get("CodeId"));//钥匙编号
                            sendMap.put("date", InteDeviceLockUtil.getTimeSign());//当前时间(毫秒数)
                            if(IntelligentOpenType==0){
                                sendMap.put("keyId", InteMap.get("CodeId"));//钥匙编号
                                Map<String, Object> mapResult = InteDeviceLockUtil.keyUnauthorize(sendMap);
                                System.out.println("钥匙返回的参数:" + mapResult);
                                System.out.println("InteMap1:" + InteMap);
                                if (mapResult.get("errcode") != null && mapResult.get("errcode").toString().equals("0")) {
                                    result.putSuccess("科技侠智能门锁解除授权成功");
                                } else {
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return result.putFailed(mapResult.get("errmsg").toString());
                                }



                            }else if(IntelligentOpenType ==1){//表示密码
                                sendMap.put("keyboardPwdId", InteMap.get("CodeId"));//钥匙编号
                                Map<String, Object> mapResult = InteDeviceLockUtil.keyboardPwdDelete(sendMap);
                                System.out.println("钥匙返回的参数:" + mapResult);
                                System.out.println("InteMap1:" + InteMap);
                                if (mapResult.get("errcode") != null && mapResult.get("errcode").toString().equals("0")) {
                                    result.putSuccess("科技侠智能门锁解除授权成功");
                                } else {
                                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                    return result.putFailed(mapResult.get("errmsg").toString());
                                }

                            }



                        } else if (InteMap.get("Intelligent").toString().equals("3")) {//果加
                            String GuoJiaToken = redisUtils.get("GuoJiaToken");
                            //如果获取不到就重新登录
                            if (GuoJiaToken == null) {
                                Map<String, Object> guoJiaMap = new HashMap<String, Object>();
                                guoJiaMap.put("s_id", InteGuoJiaUtil.getSid());
                                guoJiaMap.put("version", "1");
                                com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                                //key
                                DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
                                //密码
                                bodyJson.put("account", InteGuoJiaConfig.ACCOUNT);
                                bodyJson.put("password", desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
                                guoJiaMap = InteGuoJiaUtil.login(guoJiaMap, bodyJson);
                                //返回的token数据
                                Map<String, Object> dataMap = (Map<String, Object>) guoJiaMap.get("data");
                                if (guoJiaMap.get("rlt_code").toString().equals("HH0000")) {//HH0000 、成功
                                    GuoJiaToken = dataMap.get("access_token").toString();
                                    //token存到redis中
                                    redisUtils.set("GuoJiaToken", GuoJiaToken, Long.valueOf(dataMap.get("expires_second").toString()));
                                } else {
                                    return result.putFailed("token获取失败");
                                }
                            }
                            /*解除果加的门锁授权*/
                            Map<String, Object> headParams = new HashMap<String, Object>();
                            headParams.put("s_id", InteGuoJiaUtil.getSid());
                            headParams.put("version", "1");
                            headParams.put("access_token", GuoJiaToken);


                            if (IntelligentOpenType==0){
                                com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                                bodyJson.put("lock_no", InteMap.get("Identifier"));//智能门锁的设备编号
                                bodyJson.put("mobile", params.get("phone"));//用户手机号
                                Map<String, Object> guoJiaResult = InteGuoJiaUtil.lockCancel_auth(headParams, bodyJson);
                                if (guoJiaResult.get("rlt_code") != null && guoJiaResult.get("rlt_code").toString().equals("HH0000")) {//HH0000 、成功
                                    result.putSuccess("解除果加门锁授权成功");
                                } else {
                                    return result.putFailed(guoJiaResult.get("rlt_msg").toString());
                                }

                            }
//                            else if(IntelligentOpenType==1){
////                                com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
////                                bodyJson.put("lock_no", InteMap.get("Identifier"));//智能门锁的设备编号
////                                bodyJson.put("pwd_no", InteMap.get("CodeId"));//密码id
////                                Map<String, Object> guoJiaResult = InteGuoJiaUtil.pwd_delete(headParams, bodyJson);
////                                if (guoJiaResult.get("rlt_code") != null && guoJiaResult.get("rlt_code").toString().equals("HH0000")) {//HH0000 、成功
////                                    result.putSuccess("解除果加门锁授权成功");
////                                } else {
////                                    return result.putFailed(guoJiaResult.get("rlt_msg").toString());
////                                }
//                                result.putSuccess("离线密码无法");
//
//
//                            }


                        }
                    }
                }

//                    //智能设备供应商     0 无智能门锁   2.科技侠   3.果加
//                    if (params.get("inteType").toString().equals("2") || params.get("inteType").toString().equals("3")){
//                        //需要删除密码的数据（删除蓝牙密钥）
//                        List<Map<String,Object>> lockList=(List<Map<String,Object>>)params.get("DelIdList");
//                        //保存钥匙编号（传递到市场部修改内部系统钥匙信息）
//                        List<String> smaIdList=new ArrayList<String>();
//                        System.out.println("lockList:"+lockList);
//                        String DeviceLockToken="";//科技侠的登录token
//                        String GuoJiaToken="";//果加的登录token
//                        if (params.get("inteType").toString().equals("2")){//获取科技侠的登录token
//                            DeviceLockToken=redisUtils.get("DeviceLockToken");
//                            //如果获取不到就重新登录
//                            if (DeviceLockToken==null){
//                                Map<String,Object> tokenMap=new HashMap<String, Object>();
//                                tokenMap.put("client_id", InteDeviceLockConfig.CLIENT_ID);
//                                tokenMap.put("client_secret",InteDeviceLockConfig.CLIENT_SECRET);
//                                tokenMap.put("grant_type",InteDeviceLockConfig.GRANT_TYPE_PASSWORD);
//                                tokenMap.put("username",InteDeviceLockConfig.USERNAME);
//                                tokenMap.put("password",InteDeviceLockConfig.PASSWORD);
//                                tokenMap.put("redirect_uri",InteDeviceLockConfig.REDIRECT_URL);
//                                System.out.println("请求科技侠的参数:"+tokenMap);
//                                tokenMap=InteDeviceLockUtil.oauth2Token(tokenMap);
//                                if (tokenMap.get("access_token")!=null){
//                                    DeviceLockToken=tokenMap.get("access_token").toString();
//                                    //token存到redis中
//                                    redisUtils.set("DeviceLockToken",DeviceLockToken,Long.valueOf(tokenMap.get("expires_in").toString()));
//                                }else{
//                                    return result.putFailed("token获取失败");
//                                }
//                                Map<String,Object> lockMap=new HashMap<String,Object>();
//                                lockMap.put("clientId", InteDeviceLockConfig.CLIENT_ID);
//                                lockMap.put("accessToken",DeviceLockToken);
//                                int lockNum=0;//保存删除成功的
//                                for(Map<String,Object> map :lockList){
//                                    smaIdList.add(map.get("SmaId").toString());//钥匙编号
//                                    //智能设备供应商     2.科技侠   3.果加
//                                    //密码类型   1.键盘密码  2.蓝牙密码
//                                    if (map.get("CodeType").toString().equals("2")){
//                                        lockMap.put("keyId",map.get("CodeId"));//密码id
//                                        lockMap.put("date", InteDeviceLockUtil.getTimeSign());
//                                        Map<String,Object> inteMap=InteDeviceLockUtil.keyDelete(lockMap);
//                                        if(inteMap.get("errcode").toString().equals("0")){
//                                            lockNum++;
//                                        }
//                                    }
//                                }
//                            }
//                        }else if(params.get("inteType").toString().equals("3")) {//获取果加的登录token
//                            GuoJiaToken=redisUtils.get("GuoJiaToken");
//                            //如果获取不到就重新登录
//                            if (GuoJiaToken==null){
//                                Map<String,Object> guoJiaMap=new HashMap<String, Object>();
//                                guoJiaMap.put("s_id",InteGuoJiaUtil.getSid());
//                                guoJiaMap.put("version","1");
//                                com.alibaba.fastjson.JSONObject bodyJson=new com.alibaba.fastjson.JSONObject();
//                                //key
//                                DESEncrypt desPlus2 = new DESEncrypt(InteGuoJiaConfig.DES_KEY);
//                                //密码
//                                bodyJson.put("account",InteGuoJiaConfig.ACCOUNT);
//                                bodyJson.put("password",desPlus2.encrypt(InteGuoJiaConfig.PASSWORD));
//                                guoJiaMap=InteGuoJiaUtil.login(guoJiaMap,bodyJson);
//                                if (guoJiaMap.get("rlt_code") !=null && guoJiaMap.get("rlt_code").toString().equals("HH0000")){//HH0000 、成功
//                                    //返回的token数据
//                                    Map<String,Object>dataMap=(Map<String,Object>)guoJiaMap.get("data");
//                                    GuoJiaToken=dataMap.get("access_token").toString();
//                                    //token存到redis中
//                                    redisUtils.set("GuoJiaToken",GuoJiaToken,Long.valueOf(dataMap.get("expires_second").toString()));
//                                }else{
//                                    return result.putFailed("token获取失败");
//                                }
//                            }
//                            /*解除对用户的门锁授权*/
//                            Map<String,Object> lockMap=new HashMap<String, Object>();
//                            lockMap.put("s_id",InteGuoJiaUtil.getSid());
//                            lockMap.put("version","1");
//                            lockMap.put("access_token",GuoJiaToken);
//                            com.alibaba.fastjson.JSONObject bodyJson=new com.alibaba.fastjson.JSONObject();
//                            int lockNum=0;//保存删除成功的
//                            for(Map<String,Object> map :lockList){
//                                smaIdList.add(map.get("SmaId").toString());//钥匙编号
//                                //智能设备供应商     2.科技侠   3.果加
//                                bodyJson.put("lock_no",map.get("CodeId"));//这里相当于果加的智能设备编号
//                                bodyJson.put("mobile",map.get("Code"));//这里相当于果加用户的手机号
//                                System.out.println("果加传递lockMap:"+lockMap);
//                                System.out.println("果加传递bodyJson:"+bodyJson);
//                                Map<String,Object> inteMap=InteGuoJiaUtil.lockCancel_auth(lockMap,bodyJson);
//                                System.out.println("果加返回inteMap:"+inteMap);
//                                if(inteMap.get("rlt_code")!=null && inteMap.get("rlt_code").toString().equals("HH0000")){
//                                    lockNum++;
//                                }
//                            }
//                        }
//                        //把已删除的智能钥匙编号传递到市场部
//                        params.put("smaIdList",smaIdList);
//                        //WitType 退租账单类型   1.租客违约   2.唐巢违约（唐巢违约不需要违约金）3租客正常退
//                        //Withdrawal 退租状态   0.正常退租    1.强制退   2.违约退
//                        if (String.valueOf(params.get("WitType")).equals("1")){
//                            params.put("Withdrawal","2");
//                        }else if (String.valueOf(params.get("WitType")).equals("3")){
//                            params.put("Withdrawal","0");
//                        }
//
//                    }




                    //智能电表的数组

                    //List<Map<String,Object>> InteDeviceList=(List<Map<String,Object>>)params.get("InteDeviceList");
                    //System.out.println(InteDeviceList);
                    //如果智能电表数组不为空的就去执行大华or蜂电的退租操作
                    if (params.get("InteDeviceList")!=null){
                        List<Map<String,Object>> InteDeviceList=(List<Map<String,Object>>)params.get("InteDeviceList");
                        System.out.println(InteDeviceList);
                        //智能设备供应商     0.蜂电   1.大华   2.科技侠   3.果加
                        if (params.get("ifIntelligentDevice").toString().equals("0")){
                            String InteDeviceBeeToken=redisUtils.get("InteDeviceBeeToken");
                            //如果获取不到就重新登录
                            if (InteDeviceBeeToken==null) {
                                Map<String, Object> tokenMap = new HashMap<String, Object>();
                                params.put("version","0116010101");//版本号 默认 0116010101
                                params.put("appid", InteDeviceBeeConfig.APP_ID);
                                tokenMap=InteDeviceBeeUtil.userLogin(InteDeviceBeeConfig.USERID, InteDeviceBeeConfig.PASS,params);
                                System.out.println("tokenMap："+tokenMap);
                                if (tokenMap.get("Code").toString().equals("0")) {
                                    InteDeviceBeeToken = tokenMap.get("Expand").toString();
                                    //token存到redis中 有效时长一个小时
                                    redisUtils.set("InteDeviceBeeToken", InteDeviceBeeToken,3600);
                                } else {
                                    return result.putFailed("token获取失败");
                                }
                            }
                            //智能电表必定是每个房间都有一个电表，用房间集合的长度初始化智能电表设备编号数组
                            List<String> InteList = new ArrayList<String>();
                            Map<String, Object> headMap = new HashMap<String, Object>();
                            headMap.put("uid", InteDeviceBeeConfig.UID);//唐巢在蜂电用户ID
                            headMap.put("token", InteDeviceBeeToken);//访问令牌
                            headMap.put("version", "0116010101");//版本号默认0116010101
                            for (int i = 0; i < InteDeviceList.size(); i++) {
                                Map<String, Object> map1 = InteDeviceList.get(i);
                                if (map1.get("Identifier") != null) {
                                    InteList.add(map1.get("Identifier").toString());
                                }
                            }
                            //蜂电返回的参数
                            Map<String, Object> InteDataMap = InteDeviceBeeUtil.deviceAmmeterPcode(InteList, headMap);

                            if (InteDataMap.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                //电表数组
                                List<Map<String, Object>> InteDataList = (List<Map<String, Object>>) InteDataMap.get("Data");
                                for (Map<String, Object> map1 : InteDeviceList) {
                                    if (map1.get("Identifier") != null) {
                                        for (Map<String, Object> map2 : InteDataList) {
                                            if (map2.get("Ccode") != null) {
                                                if (map1.get("Identifier").toString().equals(map2.get("Pcode").toString())) {
                                                    map1.put("Uuid", map2.get("Uuid"));
                                                }
                                            }
                                        }
                                    }
                                }
                                System.out.println(InteDeviceList);


                                if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租,并且房间智能电表为蜂电,修改模式为预付费
                                    for (Map<String, Object> map1 : InteDeviceList) {
                                        Map<String, Object> a1 = InteDeviceBeeUtil.deviceAmmeterPaymode(map1.get("Uuid").toString(), "1", headMap);
                                        if (!a1.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                            return result.putFailed("第三方服务器繁忙");
                                        }
                                    }
                                } else if(MapUtils.getInteger(params, "ProOperaType") ==1){


                                    String Hous = MapUtils.getString(params, "HouInfoId");
                                    String HouLast = Hous.substring(Hous.length() - 1, Hous.length());
                                    for (Map<String, Object> map1 : InteDeviceList) {
                                        String HouConName = MapUtils.getString(map1, "HouConName");
                                        String HouConLast = HouConName.substring(HouConName.length() - 1, HouConName.length());
                                        if (HouLast.equals(HouConLast)) {
                                            Map<String, Object> InteDataMaps = InteDeviceBeeUtil.deviceAmmeterConfirmrecederoom(MapUtils.getString(map1, "Uuid"), headMap);
                                            if (!InteDataMaps.get("Code").toString().equals("0")) {// 0蜂电接口返回正常
                                                return result.putFailed("第三方服务器繁忙");
                                            }

                                        }
                                    }

                                }



                            }else {
                                return result.putFailed("第三方服务器繁忙");
                            }

                        } else if (params.get("ifIntelligentDevice").toString().equals("1")) {//大华
                            String InteDaHuaToken = redisUtils.get("InteDaHuaToken");
                            //如果获取不到就重新登录
                            if (InteDaHuaToken == null) {
                                /*获取token*/
                                Map<String, Object> DaParams = new HashMap<String, Object>();
                                DaParams.put("pw", InteDeviceDaHuaConfig.PW);
                                DaParams.put("userName", InteDeviceDaHuaConfig.USERNAME);
                                DaParams = InteDeviceDaHuaUtil.getToken(DaParams);
                                if (DaParams.get("code") != null && DaParams.get("code").toString().equals("1")) {//1 状态码 请求成功
                                    InteDaHuaToken = DaParams.get("data").toString();
                                    //token有效期2个小时，所有接口Code=0 ，token失效 需要重新获取
                                    redisUtils.set("InteDaHuaToken", InteDaHuaToken, 3600 * 2);
                                    System.out.println(InteDaHuaToken);
                                } else {
                                    return result.putFailed("token获取失败");
                                }
                            }

                            Map<String, Object> tokenMap = new HashMap<>();
                            tokenMap.put("token", InteDaHuaToken);

                            if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租
                                for (Map<String, Object> ceshiMap : InteDeviceList) {
                                    com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                                    bodyJson.put("meter_id", ceshiMap.get("Identifier"));
                                    bodyJson.put("tra_id", Calendar.getInstance().getTimeInMillis());
                                    bodyJson.put("token", InteDaHuaToken);

                                    Map<String, Object> getParams = InteDeviceDaHuaUtil.clearIntefers(tokenMap, bodyJson);
                                    if (!(getParams.get("code") != null && getParams.get("code").toString().equals("1"))) {//0 状态码 请求成功
                                        return result.putFailed("第三方服务器繁忙");
                                    }
                                }
                            } else {//表示合租,只用清空自己房间的电表余额

                                String Hous = MapUtils.getString(params, "HouInfoId");
                                String HouLast = Hous.substring(Hous.length() - 1, Hous.length());

                                for (Map<String, Object> ceshiMap : InteDeviceList) {
                                    String HouConName = MapUtils.getString(ceshiMap, "HouConName");
                                    String HouConLast = HouConName.substring(HouConName.length() - 1, HouConName.length());

                                    if (HouLast.equals(HouConLast)) {

                                        com.alibaba.fastjson.JSONObject bodyJson = new com.alibaba.fastjson.JSONObject();
                                        bodyJson.put("meter_id", ceshiMap.get("Identifier"));
                                        bodyJson.put("tra_id", Calendar.getInstance().getTimeInMillis());
                                        bodyJson.put("token", InteDaHuaToken);
                                        Map<String, Object> getParams = InteDeviceDaHuaUtil.clearIntefers(tokenMap, bodyJson);
                                        if (!(getParams.get("code") != null && getParams.get("code").toString().equals("1"))) {//0 状态码 请求成功
                                            return result.putFailed("第三方服务器繁忙");
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //去市场部修改合同的相关信息
                    JsonResult marketResult=zpcMktFeign.updatePactRent(params);
                    if (marketResult.get("errorCode")==null || !marketResult.get("errorCode").toString().equals("0")){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return result.put("服务器繁忙");
                    }

                    Map<String, TemplateData> param = new HashMap<>();
                    param.put("first", new TemplateData("唐巢公寓温馨提示：尊敬的租客，退租提醒\n", "#4876FF"));
                    param.put("keyword1", new TemplateData(params.get("ComName").toString(), "#4876FF"));
                    param.put("keyword2", new TemplateData(params.get("Address").toString(), "#4876FF"));
                    param.put("keyword3", new TemplateData(params.get("instm").toString(), "#4876FF"));
                    param.put("keyword4", new TemplateData(params.get("instm").toString(), "#4876FF"));
                    Jsapi_ticketUtil.sendTemplate(params.get("openid").toString(), WeChatConfig.RENTPACT_ID,"http://www.4006269069.net/#/terminationDetail?PaId="+params.get("PaId"),"#4876FF", JSONObject.fromObject(param));
                    //修改账单为废弃
                    params.put("Source",params.get("PaId"));//账单来源编号
                    params.put("Status",4);//账单状态   1.待支付  2.支付完成  3待审核   4.账单废弃（租客违约）
                    params.put("delfg",1);//废弃标志位  0正常 1废弃
                    //未支付账单列表状态改为合并至退租账单,
                    if (params.get("notpaidList")!=null){
                        List<Map<String,Object>> notpaidList=(List<Map<String,Object>>)params.get("notpaidList");
                        for(Map<String,Object> noMap:notpaidList){
                            noMap.put("Status","6");//账单状态   1.待支付  2.支付完成  3待审核   4.账单废弃（租客违约）5审核驳回
                            noMap.put("delfg","1");//废弃标志位  0正常 1废弃
                            noMap.put("by", userId);//操作人
                            noMap.put("term", "4");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
                            noMap.put("fnc",
                                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                            ParamsCommon.commonUpdateParms(noMap);
                           // noMap.put("Source",params.get("BiId"));
                            noMap.put("Sourcesss",UUID);//不改变最后生成的退租账单
                            hoTenantBillMapper.updateHoStatusDelfg(noMap);
                        }
                    }
                    result.putSuccess("操作成功");
                }







            } catch (Exception e) {
                result.putSuccess("服务器繁忙");
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

        }finally {
            lock.unlock();
        }


        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult ceshishuidianran(Map<String, Object> params) {
        JsonResult result = new JsonResult();

        //参数,EleMap,WatMap,GasMap


//                WatMap{
//
//                    "HouId",
//                    "HouInfoId",
//                "LastMonthRead",
//                "ThisMonthRead",
//
//
//                }

        //先走水费
        lock.lock();

        try {


            String UUID= "woyaoceshi1";
            if (params.get("WatMap")!=null) {
                Map<String, Object> WatMap = (Map<String, Object>) params.get("WatMap");

                String WatmeIdUUID = "";//水费抄表编号
                String BatchIdUUID = "";//水费抄表批次编号
                Map<String, Object> WameIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                    put("uuid", "WameId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_water_meter");
                }});

                if (WameIduuid != null) {
                    int number = Integer.valueOf(WameIduuid.get("uuid").toString());
                    WatmeIdUUID = ComUtils.getLocalTrmSeqNum("WM0", number);
                    BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", number);
                } else {
                    WatmeIdUUID = ComUtils.getLocalTrmSeqNum("WM0", 0);
                    BatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", 0);
                }
                WatMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                WatMap.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(WatMap);
                WatMap.put("WameId", WatmeIdUUID);//水费抄表编号
                WatMap.put("BatchId", BatchIdUUID);//水费抄表批次编号
                WatMap.put("MeTypeId", UUID);//来源编号
                WatMap.put("IfMeter", 1);//是否是退租抄表

                // Watmap.put("HouId",map1.get("HouId"));//房源编号
                // Watmap.put("HouInfoId", map1.get("HouInfoId"));//房源详表编号
                WatMap.put("IfOperaType", 1);//是否整租 0否 1是 2秘书抄表
                //  Watmap.put("StaTime",map1.get("GenerateTime"));//账单起时间
                // Watmap.put("EndTime",GenerateTimeNow);//账单止时间
                //  Watmap.put("LastMonthRead",map1.get("LastMonthRead"));//上月总表数
                // Watmap.put("ThisMonthRead", map1.get("ThisMonthRead"));//本次总表数
                WatMap.put("MeterRole", 2);//抄表人角色0租赁顾问 1服务秘书 2服务管家
                //  Watmap.put("BillMoney",billMoney);//账单金额.所有租客一共需支付的金额
                WatMap.put("GenerateTime", params.get("StartingTime"));//抄表日期
                WatMap.put("Recorder", ContextUtils.getUserId());//记录人编号

                WatMap.put("IfGenerate", 1);//是否生成账单 0未生成 1已生成

                if (MapUtils.getInteger(params, "ProOperaType") == 1 && MapUtils.getInteger(params, "MoviesType") == 1) {//合租非智能
                    //总的均摊量
                    Double  WatPooledSum = CompuUtils.reduce(MapUtils.getDouble(WatMap,"ThisMonthRead"),MapUtils.getDouble(WatMap,"LastMonthRead"));
                    Double WatPooled = new Double("0");//在租房间的均摊电量

                    WatMap.put("IfApportion", 1);//是否需要分摊0否 1是
                    Integer a1 = hoWaterMeterMapper.addHoWaterMeter(WatMap);
                    if (a1<=0){
                        return  result.putFailed("新增水抄表失败");
                    }
                    List<Map<String,Object>> getHouPact = zpcMktFeign.getHouPact(WatMap);
                    if (getHouPact.size()>0){
                        //在租房间的均摊量
                        WatPooled = CompuUtils.div(WatPooledSum,new Double(getHouPact.size()),2);
                    }
                    for(Map<String,Object> map1:getHouPact){
                        String WatPooledIduuid = "";
                        Map<String, Object> PooledIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                            put("uuid", "WatPooledId");
                            put("database", Constants.DATA_SOURCE_GMIO);
                            put("surface", "tcgmio_water_meter_Pooled");
                        }});

                        if (PooledIduuid != null) {
                            int number = Integer.valueOf(PooledIduuid.get("uuid").toString());
                            WatPooledIduuid = ComUtils.getLocalTrmSeqNum("WP", number);
                        } else {
                            WatPooledIduuid = ComUtils.getLocalTrmSeqNum("WP", 0);
                        }

                        Map<String,Object> WatPolMap = new HashMap<>();
                        WatPolMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                        WatPolMap.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(WatPolMap);

                        WatPolMap.put("WatPooledId", WatPooledIduuid);//公摊水表编号
                        WatPolMap.put("WameId",WatMap.get("WameId"));//水抄表编号
                        WatPolMap.put("BatchId", WatMap.get("BatchId"));//水抄表批次编号
                        WatPolMap.put("TenId", map1.get("TenId"));//租客编号
                        WatPolMap.put("HouId", map1.get("HouId"));//房源编号
                        WatPolMap.put("HouInfoId", map1.get("HouInfoId"));//房源详表编号
                        WatPolMap.put("WatPooled", WatPooled);//公摊用水量
                        WatPolMap.put("WatMetMoney",CompuUtils.mul(MapUtils.getDouble(map1,"WaterPricing"),WatPooled));//记录在租房间的公摊水费
                        WatPolMap.put("PoolTime", params.get("StartingTime"));//公摊生成时间

                        if (params.get("TenId").equals(map1.get("TenId"))){
                            Double WatMetMoney = MapUtils.getDouble(WatPolMap,"WatMetMoney");
                            List<Map<String,Object>> getPooledList=hoPooledMapper.getPooledList(map1);//查询租客未生成账单的公摊费用
                            if (getPooledList.size()>0){//表示本次抄表之前有公摊费用未生成账单,要加上之前的公摊费用一起生成账单,
                                for (Map<String,Object> map2:getPooledList){
                                    WatMetMoney = CompuUtils.add(WatMetMoney,MapUtils.getDouble(map2,"WatMetMoney"));
                                    //修改公摊费用为已生成账单
                                    Map<String,Object> PoolMap = new HashMap<>();
                                    PoolMap.put("term","4");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                                    PoolMap.put("fnc",
                                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                                    ParamsCommon.commonUpdateParms(PoolMap);
                                    PoolMap.put("WatPooledId",map2.get("WatPooledId"));//公摊账单编号
                                    PoolMap.put("Status",1);//租客水费公摊表已生成账单
                                    PoolMap.put("IfGenerate",1);//水抄表已生成账单
                                    Integer a8 = hoPooledMapper.updateWatPooled(PoolMap);
                                    if (a8<=0){
                                        return result.putFailed("修改租客公摊表失败");

                                    }

                                }
                            }

                            WatPolMap.put("WatMetMoney",WatMetMoney);//是否生成账单0未生成1已生成
                            WatPolMap.put("Status", 1);//是否生成账单0未生成1已生成

                        }else{//其他房间生成均摊不生成账单
                            WatPolMap.put("Status", 0);//是否生成账单0未生成1已生成

                        }
                        Integer a2 = hoPooledMapper.addWatPooled(WatPolMap);
                        if (a2<=0){
                            return result.putFailed("新增房间公摊表失败");
                        }

                    }
                } else if (MapUtils.getInteger(params, "ProOperaType") == 2) {//整租抄水费
                    WatMap.put("IfApportion", 0);//是否需要分摊0否 1是
                    Integer a3 = hoWaterMeterMapper.addHoWaterMeter(WatMap);
                    if (a3<=0){
                        return result.putFailed("新增整租水抄表失败");
                    }
                }

            }

//                GasMap{
//                    "HouId",
//                    "HouInfoId",
//                "LastMonthRead",
//                "ThisMonthRead",
//
//
//                }

            //在走燃气费
            if (MapUtils.getInteger(params,"ProOperaType")==2){//整租记录本次燃气费

                if (params.get("GasMap")!=null) {
                    Map<String,Object> GasMap = (Map<String, Object>) params.get("GasMap");
                    String GasmeIdUUID = "";//燃气抄表编号
                    String GasBatchIdUUID = "";//燃气抄表批次编号
                    Map<String, Object> GasmeIduuid = utilsMapper.getUUID(new HashMap<String, Object>() {{
                        put("uuid", "GasmeId");
                        put("database", Constants.DATA_SOURCE_GMIO);
                        put("surface", "tcgmio_gas_meter");
                    }});

                    if (GasmeIduuid != null) {
                        int number = Integer.valueOf(GasmeIduuid.get("uuid").toString());
                        GasmeIdUUID = ComUtils.getLocalTrmSeqNum("GM0", number);
                        GasBatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", number);
                    } else {
                        GasmeIdUUID = ComUtils.getLocalTrmSeqNum("GM0", 0);
                        GasBatchIdUUID = ComUtils.getLocalTrmSeqNum("BA0", 0);
                    }

                    GasMap.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                    GasMap.put("fnc",
                            this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                    ParamsCommon.commonInsertParms(GasMap);
                    GasMap.put("GasmeId", GasmeIdUUID);//燃气费抄表编号
                    GasMap.put("BatchId", GasBatchIdUUID);//批次编号
                    GasMap.put("IfOperaType", 1);//是否整租0否1是
                    GasMap.put("MeTypeId",UUID);//来源编号
                    GasMap.put("IfMeter",1);//退租抄表
                    //GasMap.put("MeterRole",2);//退租抄表
                    //GasMap.put("StaTime",2);//账单起时间
                    //GasMap.put("EndTime",2);//账单止时间
                    GasMap.put("MeterRole", 2);//抄表人角色2服务管家
                    GasMap.put("Recorder", ContextUtils.getUserId());//记录人编号
                    GasMap.put("IfApportion", 0);//是否需要分摊0否1是
                    GasMap.put("IfGenerate", 1);//是否生成账单
                    GasMap.put("GenerateTime", params.get("StartingTime"));
                    Integer a4 = hoGasMeterMapper.addHoGasMeter(GasMap);//记录最后一次管家退租的抄表数
                    if (a4<=0){
                        return result.putFailed("新增燃气抄表数失败");
                    }

                }

            }

//
//                EleMap{
//                 "HouId"
//                 "HouInfoId"
//                `LastMonthEleSum`  '上月总表',
//                `LastMonthElePeak` '上月峰时',
//                `LastMonthEleFlat` '上月谷时',
//                `ThisMonthEleSum`  '总表   （不能低于上月）',
//                `ThisMonthElePeak`  '峰时   （不能低于上月）',
//                `ThisMonthEleFlat` '谷时',
//                "roomData":[
//                    "HouInfoId":
//                    `LastMonthEleSum`  '上月总表',
//                    `ThisMonthEleSum`  '总表   （不能低于上月）',
//                        ]
//                }

            //在走电费
            if (params.get("EleMap") !=null){
                Map<String,Object> EleMap = (Map<String, Object>) params.get("EleMap");

                String Eleus  = "";//电费抄表批次编号
                //电
                Map<String,Object> Eleuuid =utilsMapper.getUUID(new HashMap<String,Object>(){{
                    put("uuid", "ElemeId");
                    put("database", Constants.DATA_SOURCE_GMIO);
                    put("surface", "tcgmio_ele_meter");
                }});
                int numberss = 0;
                if(Eleuuid!=null){
                    numberss=Integer.valueOf(Eleuuid.get("uuid").toString());
                    Eleus = ComUtils.getLocalTrmSeqNum("BA0",numberss);
                }else{
                    Eleus = ComUtils.getLocalTrmSeqNum("BA0",0);
                }

                Map<String,Object> EleWater = new HashMap<>();//先生成公共区域的
                EleWater.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                EleWater.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(EleWater);
                EleWater.put("ElemeId", ComUtils.getLocalTrmSeqNum("EM" + 0, numberss));//电费抄表编号(公共区域)
                EleWater.put("BatchId", Eleus);//批次编号
                EleWater.put("HouId", EleMap.get("HouId"));//房源编号
                EleWater.put("HouInfoId", EleMap.get("HouInfoId"));//公共区域的房源详表编号
                EleWater.put("IfOperaType", 1);//是否整租0否1是
                EleWater.put("MeTypeId", UUID);//来源编号
                EleWater.put("IfMeter", 1);//是退租抄表
                EleWater.put("LastMonthEleSum", EleMap.get("LastMonthEleSum"));//上次总表
                EleWater.put("LastMonthElePeak", EleMap.get("LastMonthElePeak"));//上次峰表
                EleWater.put("LastMonthEleFlat", EleMap.get("LastMonthEleFlat"));//上次谷表
                EleWater.put("ThisMonthEleSum", EleMap.get("ThisMonthEleSum"));//总表
                EleWater.put("ThisMonthElePeak", EleMap.get("ThisMonthElePeak"));//峰表
                EleWater.put("ThisMonthEleFlat", EleMap.get("ThisMonthEleFlat"));//谷表
                EleWater.put("GenerateTime", params.get("StartingTime"));//抄表日期
                EleWater.put("MeterRole", 2);//服务管家
                EleWater.put("Recorder", ContextUtils.getUserId());//记录人编号
                EleWater.put("IfGenerate", 1);//是否生成账单0未生成 1已生成
                if (MapUtils.getInteger(params,"ProOperaType")==1&&MapUtils.getInteger(params,"MoviesType")==1) {//表示合租非智能

                    //先生成合租非智能的公共区域的
                    Double perEleSum = CompuUtils.reduce(MapUtils.getDouble(EleMap,"ThisMonthEleSum"),MapUtils.getDouble(EleMap,"LastMonthEleSum"));
                    // Double perELeMoney = CompuUtils.mul(perEleSum,MapUtils.getDouble(params,"EleFee"));
                    EleWater.put("perEleSum", perEleSum);//公摊电量
                    // EleWater.put("perELeMoney", perELeMoney);//公摊金额
                    hoEleMeterMapper.addHoEleMeter(EleWater);

                    //在生成房间的
                    List<Map<String, Object>> getHouPact = zpcMktFeign.getHouPact(EleMap);//获取房源在租租客
                    List<Map<String, Object>> roomData = (List<Map<String, Object>>) EleMap.get("roomData");

                    Double lastSum = new Double("0");
                    Double NowSum = new Double("0");
                    for (Map<String, Object> map5 : roomData) {
                        lastSum = CompuUtils.add(lastSum, MapUtils.getDouble(map5, "LastMonthEleSum"));
                        NowSum = CompuUtils.add(NowSum, MapUtils.getDouble(map5, "ThisMonthEleSum"));
                    }
                    //本次总的均摊
                    Double ElePooled = CompuUtils.reduce(CompuUtils.reduce(MapUtils.getDouble(EleMap, "ThisMonthEleSum"), NowSum), CompuUtils.reduce(MapUtils.getDouble(EleMap, "LastMonthEleSum"), lastSum));
                    //获取在租房间本次管家抄表的均摊电量
                    Double perELeSum = CompuUtils.div(ElePooled, new Double(getHouPact.size()), 2);





                    for (int i = 0; i < roomData.size(); i++) {
                        Map<String, Object> roomMapone = new HashMap<>();
                        roomMapone.put("term", "4");//创建端  1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                        roomMapone.put("fnc",
                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                        ParamsCommon.commonInsertParms(roomMapone);
                        roomMapone.put("ElemeId", ComUtils.getLocalTrmSeqNum("EM" + (i + 1), numberss));//电费抄表编号(公共区域)
                        roomMapone.put("BatchId", Eleus);//批次编号
                        roomMapone.put("MeTypeId", UUID);//来源编号
                        roomMapone.put("IfMeter", 1);//是退租抄表
                        roomMapone.put("HouId", EleWater.get("HouId"));//房源编号
                        roomMapone.put("HouInfoId", roomData.get(i).get("HouInfoId"));//其他房间的房源详表编号
                        roomMapone.put("IfOperaType", 0);//是否整租0否1是
                        roomMapone.put("LastMonthEleSum", roomData.get(i).get("LastMonthEleSum"));//上次总表
                        roomMapone.put("ThisMonthEleSum", roomData.get(i).get("ThisMonthEleSum"));//总表
                        roomMapone.put("MeterRole", 2);//服务管家
                        roomMapone.put("GenerateTime", params.get("StartingTime"));//抄表日期
                        roomMapone.put("Recorder", ContextUtils.getUserId());//记录人编号
                        for (Map<String, Object> map8 : getHouPact) {//该房源在租房间
                            //表示退租的房间刚好是操作的
                            if (roomMapone.get("HouInfoId").equals(MapUtils.getString(map8, "HouInfoId"))&&
                                    roomMapone.get("HouInfoId").equals(MapUtils.getString(params,"HouInfoId"))&&
                                    MapUtils.getString(map8, "HouInfoId").equals(MapUtils.getString(params,"HouInfoId"))
                            ) {


                                Double ceshi = CompuUtils.add(perELeSum,CompuUtils.reduce(MapUtils.getDouble(roomMapone,"ThisMonthEleSum"),MapUtils.getDouble(roomMapone,"LastMonthEleSum")));
                                roomMapone.put("IfGenerate", 1);//是否生成账单0未生成 1已生成
                                roomMapone.put("perELeSum", ceshi);//房间均摊电量
                                roomMapone.put("perELeMoney", CompuUtils.mul(ceshi, MapUtils.getDouble(map8, "EleFee")));//房间均摊金额

                                Double perELeMoney = MapUtils.getDouble(roomMapone,"perELeMoney");


                                List<Map<String,Object>> getElePoodList = hoEleMeterMapper.getHouInEle(map8);//获取房间已生成均摊未生成账单的抄表编号
                                if (getElePoodList.size()>0){
                                    for (Map<String,Object> map2:getElePoodList){
                                        perELeMoney = CompuUtils.add(perELeMoney,MapUtils.getDouble(map2,"perELeMoney"));//获取当前在租组可所租房间的之前的未生成账单的均摊两



                                        //修改未生成账单的均摊量为已生成账单
                                        Map<String,Object> EleMaps = new HashMap<>();
                                        EleMaps.put("term","4");//1 租客端 2市场部 3 工程部 4运营部 5财务部 6总经办 7发展部
                                        EleMaps.put("fnc",
                                                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                                        ParamsCommon.commonUpdateParms(EleMaps);
                                        EleMaps.put("IfGenerate",1);//1表示生成账单 0未生成账单
                                        EleMaps.put("ElemeId",map2.get("ElemeId"));//电抄表编号
                                        Integer a1 = hoEleMeterMapper.updateHoEleDelfg(EleMaps);
                                        if (a1>0){
                                            result.putSuccess("修改该房源之前未生成均摊的电量成功");
                                        }else {
                                            return result.putFailed("修改该房源之前未生成均摊的电量失败");
                                        }

                                    }

                                }
                                roomMapone.put("perELeMoney",perELeMoney);//房间均摊金额
                            }
                            if (roomMapone.get("HouInfoId").equals(MapUtils.getString(map8,"HouInfoId"))&&!roomMapone.get("HouInfoId").equals(MapUtils.getString(params,"HouInfoId"))){
                                Double ceshi = CompuUtils.add(perELeSum,CompuUtils.reduce(MapUtils.getDouble(roomMapone,"ThisMonthEleSum"),MapUtils.getDouble(roomMapone,"LastMonthEleSum")));
                                roomMapone.put("IfGenerate", 0);//是否生成账单0未生成 1已生成
                                roomMapone.put("perELeSum", ceshi);//房间均摊电量
                                roomMapone.put("perELeMoney", CompuUtils.mul(ceshi, MapUtils.getDouble(map8, "EleFee")));//房间均摊金额
                            }
                        }
                        hoEleMeterMapper.addHoEleMeter(roomMapone);//记录本次房间抄表
                    }

                }else if (MapUtils.getInteger(params,"ProOperaType")==2){//表示整租
                    //只生成公共区域的
                    Double perEleSum = CompuUtils.reduce(MapUtils.getDouble(EleMap,"ThisMonthEleSum"),MapUtils.getDouble(EleMap,"LastMonthEleSum"));
                    Double perELeMoney = CompuUtils.mul(perEleSum,MapUtils.getDouble(params,"EleFee"));
                    EleWater.put("perEleSum", perEleSum);//公摊电量
                    EleWater.put("perELeMoney", perELeMoney);//公摊金额
                    hoEleMeterMapper.addHoEleMeter(EleWater);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return result;
    }

    /**
     * 管家退租计算电费
     * @param params
     * @return
     */
    @Override
    public JsonResult EleLeave(Map<String, Object> params) {
//        {
//            HouId
//            HouInfoId
//            `ProOperaType` int(1) DEFAULT '1' COMMENT '租赁类型（1.合租 2.整租）',
//            MoviesType电表类型（0 智能 1非智能
//           EleFee
//            EleMap:
//            {
//                HouInfoId
//                        LastMonthEleSum
//                LastMonthElePeak
//                        LastMonthEleFlat
//                ThisMonthEleSum
//                        ThisMonthElePeak
//                ThisMonthEleFlat
//                "roomData":[
//                {
//                    HouInfoId
//                            LastMonthEleSum
//                    ThisMonthEleSum
//
//                }
//
//                         ]
//
//            }
//        }

        JsonResult result = new JsonResult();
        Map<String,Object>  EleLeaveMap = new HashMap<>();
        Double EleWithBill = new Double("0");
        Map<String,Object> EleMap = (Map<String, Object>) params.get("EleMap");//电费抄表集合
        if (MapUtils.getInteger(params,"ProOperaType")==2){
            EleWithBill=  CompuUtils.mul(MapUtils.getDouble(params,"EleFee"),CompuUtils.reduce(MapUtils.getDouble(EleMap,"ThisMonthEleSum"),MapUtils.getDouble(EleMap,"LastMonthEleSum")));

        }else{
            if(MapUtils.getInteger(params,"MoviesType")==1){//非智能
                Double a1 = new Double("0");//本次房间
                Double a2 = new Double("0");//上次房间

                List<Map<String,Object>> roomData = (List<Map<String, Object>>) EleMap.get("roomData");
                Double lastSum = new Double("0");
                Double ThisSum = new Double("0");
                for (Map<String,Object> map1:roomData){
                    lastSum = CompuUtils.add(lastSum,MapUtils.getDouble(map1,"LastMonthEleSum"));
                    ThisSum = CompuUtils.add(ThisSum,MapUtils.getDouble(map1,"ThisMonthEleSum"));
                    if(map1.get("HouInfoId").equals(params.get("HouInfoId"))){
                        a1 = MapUtils.getDouble(map1,"ThisMonthEleSum");
                        a2 = MapUtils.getDouble(map1,"LastMonthEleSum");
                    }

                }

                Double roomMoney = CompuUtils.mul(CompuUtils.reduce(a1,a2),MapUtils.getDouble(params,"EleFee"));

                Double zongSum = CompuUtils.reduce( CompuUtils.reduce(MapUtils.getDouble(EleMap,"ThisMonthEleSum"),ThisSum),CompuUtils.reduce(MapUtils.getDouble(EleMap,"LastMonthEleSum"),lastSum));
                Double ElePooled = new Double("0");
                Double ElePooledMoney = new Double("0");//本次分摊的金额
                List<Map<String,Object>> getHouPact = zpcMktFeign.getHouPact(params);
                if (getHouPact.size()>0){
                    //在租房间的均摊量
                    ElePooled = CompuUtils.div(zongSum,new Double(getHouPact.size()),2);
                    ElePooledMoney = CompuUtils.mul(ElePooled,MapUtils.getDouble(params,"EleFee"));
                }


                List<Map<String,Object>> getElePoodList = hoEleMeterMapper.getHouInEle(params);//获取房间已生成均摊未生成账单的抄表编号
                if (getElePoodList.size()>0){
                    for (Map<String,Object> map2:getElePoodList){
                        ElePooledMoney = CompuUtils.add(ElePooledMoney,MapUtils.getDouble(map2,"perELeMoney"));//获取当前在租组可所租房间的之前的未生成账单的均摊两
                    }
                }
                EleWithBill = CompuUtils.add(roomMoney,ElePooledMoney);
                 }
        }

        EleLeaveMap.put("EleWithBill",EleWithBill);
        return result.put(EleLeaveMap);

    }

    /**
     * 管家退租计算水费
     * @param params
     * @return
     */
    @Override
    public JsonResult WatLeave(Map<String, Object> params) {
//
//              "TenId"
//              "HouId":"FY-201912020002",//房源编号
//                "HouInfoId":"TFY03330440004A",//退租房间编号
//                "LastMonthRead":"8",
//                "ThisMonthRead":"12"
  //      "WaterPricing"://水费定价
  //      MoviesType 0智能 1非智能
//        ProOperaType 1合租 2整租
//

        Map<String,Object> WatMap = new HashMap<>();
        Double WatLeaveMoney = new Double("0");

        JsonResult result = new JsonResult();
      if(MapUtils.getInteger(params,"ProOperaType")==2){
          //表示整租
          WatLeaveMoney=  CompuUtils.mul(MapUtils.getDouble(params,"WaterPricing"),CompuUtils.reduce(MapUtils.getDouble(params,"ThisMonthRead"),MapUtils.getDouble(params,"LastMonthRead")));
      }else{//表示合租,
          if(MapUtils.getInteger(params,"MoviesType")==1){//非智能

              Double  WatPooledSum = CompuUtils.reduce(MapUtils.getDouble(params,"ThisMonthRead"),MapUtils.getDouble(params,"LastMonthRead"));
             Double WatPooled = new Double("0");
             Double WatPooledMoney = new Double("0");
              List<Map<String,Object>> getHouPact = zpcMktFeign.getHouPact(params);
              if (getHouPact.size()>0){
                  //在租房间的均摊量
                  WatPooled = CompuUtils.div(WatPooledSum,new Double(getHouPact.size()),2);
                  WatPooledMoney = CompuUtils.mul(WatPooled,MapUtils.getDouble(params,"WaterPricing"));
              }


              List<Map<String,Object>> getPooledList=hoPooledMapper.getPooledList(params);//查询租客未生成账单的公摊费用
              if (getPooledList.size()>0){//表示本次抄表之前有公摊费用未生成账单,要加上之前的公摊费用一起生成账单,
                  for (Map<String,Object> map2:getPooledList){
                      WatPooledMoney = CompuUtils.add(WatPooledMoney,MapUtils.getDouble(map2,"WatMetMoney"));


                  }
              }

              WatLeaveMoney = WatPooledMoney;

          }

      }
        WatMap.put("WatWithBill",WatLeaveMoney);
        return result.put(WatMap);


    }

    /**
     * 管家退租计算燃气费
     * @param params
     * @return
     */
    @Override
    public JsonResult GasLeave(Map<String, Object> params) {
//
//              "TenId"
//              "HouId":"FY-201912020002",//房源编号
//                "HouInfoId":"TFY03330440004A",//退租房间编号
//                "LastMonthRead":"8",
//                "ThisMonthRead":"12"
//                "GasPricing"://水费定价
//              MoviesType 0智能 1非智能
//             ProOperaType 1合租 2整租
//
//EleWithBill


        JsonResult result = new JsonResult();
        Map<String,Object> GasMap = new HashMap<>();
        Double GasWithBill = new Double("0");

        if(MapUtils.getInteger(params,"ProOperaType")==2){
            //表示整租
            GasWithBill=  CompuUtils.mul(MapUtils.getDouble(params,"GasPricing"),CompuUtils.reduce(MapUtils.getDouble(params,"ThisMonthRead"),MapUtils.getDouble(params,"LastMonthRead")));

        }
        GasMap.put("GasWithBill",GasWithBill);
        return result.put(GasMap);

    }

    /**
     * 收费标准费用补充
     * @param params
     * @return
     */
    @Override
    public JsonResult ChargeFee(Map<String, Object> params) {
        JsonResult result =new JsonResult();
       return result.put(hoHousekeeperMapper.getChargeFee(params));

    }

    /**
     * 未缴夜间开门费
     * @param params
     * @return
     */
    @Override
    public JsonResult getNightRoom(Map<String, Object> params) {
//        TenId;
//        HouId;
//        HouInfoId;
        JsonResult result = new JsonResult();
        params.put("Status",1);//待支付
       Map<String,Object> map1 = hoHousekeeperMapper.getNightRoom(params);
       Double Money1= MapUtils.getDouble(map1,"NightMoney");
        params.put("Status",2);//已支付
        Map<String,Object> map2 = hoHousekeeperMapper.getNightRoom(params);
        Double Money2= MapUtils.getDouble(map2,"NightMoney");
        Double NightMoneys = CompuUtils.reduce(Money1,Money2);//未缴
        params.put("NightMoney",NightMoneys);
        return result.put(params);


    }

}
